package com.powernode.queryops;

import com.powernode.commons.util.ReleaseResourceUtils;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;

/**
 * @Author Arrebol
 * @Date 2024/8/1 13:39
 * @Project jdbc
 * @Description：
 * 以指定类型从查询结果集中获取数据
 */
public class JdbcTest2 {
    public static void main(String[] args) {
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        try {
            Class.forName(driver);
            DriverManager.getConnection(url,user,password);
            conn=DriverManager.getConnection(url,user,password);
            stmt=conn.createStatement();
            String sql1="select id,name,price,create_time from t_product";

            var format=new SimpleDateFormat("yyyy/MM/dd");
            rs = stmt.executeQuery(sql1);
            while(rs.next()){
                //以特定的类型获取数据
                long id = rs.getLong("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                //从MySQL中获取的日期类型数据对应的数据类型时java.sql.Date
                //不是java.util.Date
                Date createTime= rs.getDate("create_time");
                System.out.println(id+"\t"+name+"\t"+price+"\t"+createTime);
                //将java.sql.Date转换为java.util.Date————通过构造方法实现
                java.util.Date date=new java.util.Date(createTime.getTime());
                //进行格式化显示
                String dateStr = format.format(date);
                System.out.println(dateStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReleaseResourceUtils.release(rs,stmt,conn);
        }
    }
}
